import React from 'react';
import PropTypes from 'prop-types';
import { Icon, message } from 'antd';
import styles from './index.less';
import { DASH_BOARD_SOURCE, SEARCH_TYPE } from '../../../const';

class SearchBox extends React.PureComponent {
  state={
    searBoxShow: false,
    typeListShow: false,
    type: null,
    text: '',
  };

  static propTypes = {
    clickOutClose: PropTypes.bool,
  };

  static defaultProps = {
    clickOutClose: true,
  };

  // 进行搜索
  _Search=({ type = this.state.type, text = this.state.text } = {}) => {
    const {
      answerActions, answerSystem: {
        dashboardSource: { source, beforeSearchSource: oldSearchSource },
      },
      teacherInfo: { role },
    } = this.props;
    let trimText = text.trim();
    if (!trimText) {
      message.warning('输入内容不能为空');
      return;
    }
    if (type === SEARCH_TYPE.ID.VAL) {
      trimText = parseInt(trimText, 10);
      if (!trimText) {
        message.warning('mid需要为数字');
        return;
      }
    }
    // 记录离开搜索之前的页面
    let beforeSearchSource = source;
    if ([DASH_BOARD_SOURCE.SEARCH_MESSAGE_BY_MID,
      DASH_BOARD_SOURCE.SEARCH_MESSAGE_BY_NICK,
      DASH_BOARD_SOURCE.SEARCH_MESSAGE_BY_MESSAGE].find(x => x === source)) {
      beforeSearchSource = oldSearchSource;
    }
    switch (type) {
      case SEARCH_TYPE.ID.VAL:
        answerActions.searchMessageById({
          mid: trimText,
          random: Math.random(),
          beforeSearchSource,
        });
        break;
      case SEARCH_TYPE.NICK.VAL:
        answerActions.searchMessageByNick({ nick: trimText, beforeSearchSource });
        break;
      case SEARCH_TYPE.MESSAGE.VAL:
        answerActions.searchMessageByContent({
          content: trimText,
          beforeSearchSource,
          courseCategory: role,
        });
        break;
      default: break;
    }
    window.setTimeout(() => {
      this.setState({ type });
    });
  };

  // 输入框获取焦点的事件
  _inputHandleFocus=() => {
    if (this.state.text) {
      this.setState({
        typeListShow: true,
      });
    }
  };

  // 遮罩的点击事件
  _handleMaskClick=(e) => {
    e.stopPropagation();
    this._hideSearchTypeList();
  };

  _hideSearchTypeList=() => {
    this.setState({
      typeListShow: false,
    });
  };

  // 关闭搜索框
  closeSearchBox=() => {
    const {
      answerActions,
      answerSystem: {
        dashboardSource: { beforeSearchSource: source },
      },
    } = this.props;
    this.setState({
      searBoxShow: false,
      typeListShow: false,
      text: '',
    });
    source && answerActions.changeDataSource({
      source,
      beforeSearchSource: 0,
    });
  };

  // 用于方向键切换当前选中类型
  _currentChooseIndex=(upOrDown) => {
    const typeArray = Object.keys(SEARCH_TYPE).map(key => SEARCH_TYPE[key]);
    this.setState((preState) => {
      const typeIndex = typeArray.findIndex(x => x.VAL === preState.type);
      if (upOrDown > 0) {
        return {
          type: typeIndex > Object.keys(SEARCH_TYPE).length - 2
            ? typeArray[0].VAL
            : typeArray[typeIndex + 1].VAL,
        };
      }
      return {
        type: typeIndex < 1
          ? typeArray[Object.keys(SEARCH_TYPE).length - 1].VAL
          : typeArray[typeIndex - 1].VAL,
      };
    });
  };

  // 点击搜索类型事件
  _handleSearchTypeClick=({ type }) => {
    this.setState({
      typeListShow: false,
    });
    this._Search({ type });
  };

  // 取消按钮事件
  _handleCancel=() => {
    this.closeSearchBox();
  };

  // 点击标签
  _handleSearchTypeBtn=() => {
    this.setState({
      typeListShow: true,
    });
    this.input.focus();
  };

  // 搜搜图片的事件
  _handleSearchIconClick=() => {
    if (!this.state.searBoxShow) {
      this.setState({
        searBoxShow: true,
      });
      window.setTimeout(() => {
        this.input.focus();
      }, 300);
    } else {
      this._Search();
    }
  };

  // 输入框变化
  _handleInputChange=({ target: { value: text } } = {}) => {
    this.setState({
      text,
      typeListShow: !!text,
    });
  };

  // 渲染当前类型标签
  _renderSearchType=() => {
    const { type } = this.state;
    const Ctype = Object.keys(SEARCH_TYPE).map(key => SEARCH_TYPE[key]).filter(x => x.VAL === type);
    if (Ctype.length) {
      return (
        <div className={styles.currentTypeBtn} onClick={this._handleSearchTypeBtn}>
          {Ctype[0].LABEL}
        </div>
      );
    }
    return null;
  };

  // input的案件事件
  _handleKeyDown=(e) => {
    if (e.keyCode === 13 && !(e.shiftKey || e.altKey || e.ctrlKey)) {
      const type = this.state.type || SEARCH_TYPE.ID.VAL;
      this.setState({
        typeListShow: false,
      });
      this._Search({ type });
      e.preventDefault();
    }
    if (e.keyCode === 38) {
      e.preventDefault();
      this._currentChooseIndex(false);
    }
    if (e.keyCode === 40) {
      e.preventDefault();
      this._currentChooseIndex(true);
    }
  };

  // 渲染问题类型列表
  _renderTypeList=() => (
    <ul className={styles.searchType} data-show={this.state.typeListShow}>
      {Object.keys(SEARCH_TYPE).map(key => (
        <li
          key={SEARCH_TYPE[key].VAL}
          onClick={() => {
            this._handleSearchTypeClick({ type: SEARCH_TYPE[key].VAL });
          }}
          date-current={(this.state.type === SEARCH_TYPE[key].VAL).toString()}
        >
          <span>搜索[{SEARCH_TYPE[key].LABEL}]</span>
          <Icon
            type="right"
            style={{
              fontSize: '20px', padding: '0 20px',
            }}
            theme="outlined"
          />
        </li>
      ))}
    </ul>
  );

  // 渲染遮罩,主要用于点击遮罩关闭搜索框
  _renderMask=() => {
    const { searBoxShow, typeListShow } = this.state;
    const { clickOutClose } = this.props;
    if (clickOutClose && searBoxShow && typeListShow) {
      return (
        <div className={styles.mask} onClick={this._handleMaskClick} />
      );
    }
    return null;
  };

  render() {
    const { searBoxShow, text } = this.state;
    return (
      <div className={styles.baseContainer}>
        <div
          className={styles.searchBox}
          data-show={searBoxShow}
        >
          <div className={styles.main}>
            <div className={styles.inputBox}>
              <span
                onClick={this._handleSearchIconClick}
                className={styles.searchBtn}
                data-hover={!this.state.searBoxShow}
              >
                <Icon
                  type="search"
                  style={{
                    fontSize: '20px', padding: '0 10px', transform: 'rotateY(180deg)',
                  }}
                  theme="outlined"
                />
              </span>
              <input
                type="text"
                ref={(ref) => { this.input = ref; }}
                onFocus={this._inputHandleFocus}
                value={text}
                onChange={this._handleInputChange}
                onKeyDown={this._handleKeyDown}
                tabIndex={searBoxShow ? 0 : -1}
              />
            </div>
            {this._renderSearchType()}
            <div className={styles.cancel} onClick={this._handleCancel}>
                取消
            </div>
          </div>
          {this._renderTypeList()}
        </div>
        {this._renderMask()}
      </div>
    );
  }
}

export default SearchBox;
